package kuaishou

import (
	"fmt"
	"gitee.com/edodo/flysdk/api"

	"github.com/jinzhu/copier"
)

const (
	API_HOST           = "https://open.kuaishou.com"
	ACCESS_TOKEN_URL   = API_HOST + "/oauth2/access_token"
	JSCODE_SESSION_URL = API_HOST + "/oauth2/mp/code2session"
)

type KsError struct {
	Result int64 `json:"result"`
}

type KsAccessToken struct {
	KsError
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"` //seconds
	TokenType   string `json:"token_type" yaml:"token_type"`
}

type KsCode2Session struct {
	KsError
	SessionKey string `json:"session_key"`
	Openid     string `json:"open_id"`
}

func (we KsError) IsOk() bool {
	return we.Result == 1
}

func (we KsError) Err() error {
	var errMsg string
	switch we.Result {
	case 100200100:
		errMsg = "参数有误，需要检查参数是否为空或有误"
	case 100200101:
		errMsg = "验证出错，需要检查app_id和app_secret"
	}
	return fmt.Errorf("err_code=%d, err_msg=%s", we.Result, errMsg)
}

func (dat KsAccessToken) ToAccessToken() (at *api.AccessToken, e error) {
	if !dat.IsOk() {
		e = dat.Err()
		//glog.Errorf("Get access token failed: %v", e)
		return
	}
	at = new(api.AccessToken)
	copier.Copy(at, dat)
	at.Calc()
	return
}
